package com.tech.connect.api;


import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.ksy.common.utils.ApiServer;
import com.ksy.common.utils.LogTool;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by wei.chen on 2017/7/17.
 * 集中处理Api相关配置的Manager类
 */
public class ConnectApiManager {
    private static final int DEFAULT_TIMEOUT = 25;
    private static ConnectApiManager INSTANCE;
    public final String TAG = "ConnectApiManager";
    private final int MAX_LENGTH = 2500;
    private Retrofit retrofit;
    private OkHttpClient okHttpClient;

    private static ConnectApiManager getInstance() {
        if (INSTANCE == null) {
            synchronized (ConnectApiManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new ConnectApiManager();
                }
            }
        }
        return INSTANCE;
    }

    public static <T> T getApiServer(Class<T> aClass) {
        return getInstance().retrofitBuild().create(aClass);
    }

    public static ApiServer getApiServer() {
        return getApiServer(ApiServer.class);
    }

    private OkHttpClient httpClientBuild() {
        if (okHttpClient == null) {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(@NonNull String message) {
                    if (message.length() > MAX_LENGTH) {
                        for (int i = 0; i < message.length(); i += MAX_LENGTH) {
                            if (i + MAX_LENGTH < message.length())
                                LogTool.e(TAG + "->next", message.substring(i, i + MAX_LENGTH));
                            else
                                LogTool.e(TAG + "->end", message.substring(i, message.length()));
                        }
                    } else
                        LogTool.e(TAG, message);
                }
            });
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            okHttpClient = httpClientBuilder
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(@NonNull Chain chain) throws IOException {
                            return initParams(chain);
                        }
                    })
                    .addInterceptor(httpLoggingInterceptor)
                    .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .build();
        }
        return okHttpClient;
    }

    private Response initParams(@NonNull Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        CurrentInfo userInfo = CurrentInfo.getUserInfo();
        if (userInfo != null && !TextUtils.isEmpty(userInfo.token)) {
            builder.addHeader("X-ACCESS-TOKEN", userInfo.token);
        }
        Headers headers = request.headers();
        LogTool.e(headers.toString());
        request = builder
                .build();
        return chain.proceed(request);
    }

    private Retrofit retrofitBuild() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(httpClientBuild())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .baseUrl(ApiServer.Base_url)
                    .build();
        }
        return retrofit;
    }

}
